package com.example.dianproject.service.impl;

import com.example.dianproject.dto.LoginRequest;
import com.example.dianproject.dto.LoginResponse;
import com.example.dianproject.dto.RegisterRequest;
import com.example.dianproject.dto.RegisterResponse;
import com.example.dianproject.entity.SysUser;
import com.example.dianproject.entity.UserRole;
import com.example.dianproject.repository.SysUserRepository;
import com.example.dianproject.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    
    private final SysUserRepository userRepository;
    
    @Override
    public LoginResponse login(LoginRequest request) {
        try {
            log.info("开始处理登录请求: username={}, role={}", request.getUsername(), request.getRole());
            
            // 验证用户角色是否有效
            UserRole userRole;
            try {
                userRole = UserRole.valueOf(request.getRole().toUpperCase());
                log.debug("用户角色验证通过: {}", userRole);
            } catch (IllegalArgumentException e) {
                log.warn("无效的用户角色: {}", request.getRole());
                return LoginResponse.error("无效的用户角色");
            }
            
            // 查找用户并验证
            return userRepository.findByUsernameAndRole(request.getUsername(), userRole)
                .map(user -> {
                    log.debug("找到用户: userId={}, username={}, role={}", 
                            user.getUserId(), user.getUsername(), user.getRole());
                    
                    // 直接比较密码
                    if (request.getPassword().equals(user.getPassword())) {
                        log.info("用户登录成功: userId={}, username={}", user.getUserId(), user.getUsername());
                        return LoginResponse.success(user.getUserId(), user.getUsername(), user.getRole());
                    } else {
                        log.warn("密码错误: username={}", user.getUsername());
                        return LoginResponse.error("密码错误");
                    }
                })
                .orElseGet(() -> {
                    log.warn("用户不存在或角色不匹配: username={}, role={}", 
                            request.getUsername(), request.getRole());
                    return LoginResponse.error("用户名不存在或角色不匹配");
                });
                
        } catch (Exception e) {
            log.error("登录过程中发生错误: username={}", request.getUsername(), e);
            return LoginResponse.error("登录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public RegisterResponse register(RegisterRequest request) {
        try {
            log.info("开始处理注册请求: username={}, role={}", request.getUsername(), request.getRole());
            
            // 验证用户名是否已存在
            if (userRepository.existsByUsername(request.getUsername())) {
                log.warn("用户名已存在: {}", request.getUsername());
                return RegisterResponse.error("用户名已存在");
            }
            
            // 验证用户角色是否有效
            UserRole userRole;
            try {
                userRole = UserRole.valueOf(request.getRole().toUpperCase());
                log.debug("用户角色验证通过: {}", userRole);
            } catch (IllegalArgumentException e) {
                log.warn("无效的用户角色: {}", request.getRole());
                return RegisterResponse.error("无效的用户角色");
            }
            
            // 创建新用户
            SysUser newUser = new SysUser();
            newUser.setUsername(request.getUsername());
            newUser.setPassword(request.getPassword());  // 使用明文密码
            newUser.setRole(userRole);
            newUser.setCreatedTime(LocalDateTime.now());
            
            // 保存用户
            SysUser savedUser = userRepository.save(newUser);
            log.info("用户注册成功: userId={}, username={}", savedUser.getUserId(), savedUser.getUsername());
            
            return RegisterResponse.success(savedUser.getUserId());
            
        } catch (Exception e) {
            log.error("注册过程中发生错误: username={}", request.getUsername(), e);
            return RegisterResponse.error("注册失败：" + e.getMessage());
        }
    }
} 